<?php

namespace Xrfg\Api\Trading\Spot\Resources;

use App\Http\Resources\Resource;
use Illuminate\Support\Facades\Redis;
use Xrfg\Core\Trading\Spot\Models\Pair;

class TickerResource extends Resource
{
    public function toArray($request)
    {
        list($open, $close, $high, $low, $number, $total) = $this->getTicker();

        /* @var Pair $this */
        return [
            'id' => $this->id,
            'symbol' => $this->symbol,
            'coin_name' => $this->coin_name,
            'market_name' => $this->market_name,
            'open' => $open,
            'close' => $close,
            'high' => $high,
            'low' => $low,
            'number' => $number,
            'total' => $total,
        ];
    }

    private function getTicker()
    {
        /** @var Pair $this */
        $symbol = $this->symbol;
        $redis = Redis::connection();

        if (in_array($symbol, array_keys(config('huobi')))) {
            $symbol = strtolower(str_replace('/', '', $symbol));
            $ticker = $redis->get('huobi:ticker:'.$symbol);
        } else {
            $ticker = $redis->get('etf:ticker:'.$symbol);
        }

        if (!$ticker) {
            return [
                '0.00000000',
                '0.00000000',
                '0.00000000',
                '0.00000000',
                '0.00000000',
                '0.00000000',
            ];
        } else {
            $ticker = json_decode($ticker, true);

            return [
                $ticker['open'],
                $ticker['close'],
                $ticker['high'],
                $ticker['low'],
                $ticker['number'],
                $ticker['total'],
            ];
        }
    }
}
